package com.pethospital.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pethospital.dto.UserLoginDTO;
import com.pethospital.entity.User;
import com.pethospital.exception.BusinessException;
import com.pethospital.mapper.UserMapper;
import com.pethospital.service.UserService;
import com.pethospital.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private JwtUtil jwtUtil;
    
    @Value("${spring.profiles.active:dev}")
    private String activeProfile;

    @Override
    public Map<String, Object> login(UserLoginDTO loginDTO) {
        // 模拟微信登录，实际项目中需要调用微信API获取openid
        String openid;
        
        // 开发环境使用稳定的openid生成方式
        if ("dev".equals(activeProfile)) {
            // 使用昵称和头像URL的组合生成稳定的openid
            // 如果昵称为空，使用默认值
            String nickname = StrUtil.isNotBlank(loginDTO.getNickname()) ? loginDTO.getNickname() : "default_user";
            openid = "dev_" + nickname.hashCode();
            log.info("开发环境使用稳定openid: {}, 昵称: {}", openid, nickname);
        } else {
            // 生产环境仍然使用真实的微信API获取openid
            openid = "wx_" + loginDTO.getCode(); // 生产环境下应该调用微信API
            log.info("生产环境生成openid: {}, 微信code: {}", openid, loginDTO.getCode());
        }
        
        // 查询用户是否存在
        log.info("根据openid查询用户: {}", openid);
        User user = getOne(new LambdaQueryWrapper<User>().eq(User::getOpenid, openid));
        
        // 用户不存在则注册
        if (user == null) {
            log.info("用户不存在，开始注册新用户, 昵称: {}", loginDTO.getNickname());
            user = new User();
            user.setOpenid(openid);
            user.setNickname(loginDTO.getNickname());
            user.setAvatar(loginDTO.getAvatar());
            user.setGender(loginDTO.getGender());
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setStatus(1);
            
            // 保存用户
            save(user);
            log.info("新用户注册成功: {}, ID: {}", user.getNickname(), user.getId());
        } else {
            log.info("用户已存在，直接登录: {}, ID: {}", user.getNickname(), user.getId());
            // 更新用户基本信息，保持最新状态
            boolean needUpdate = false;
            
            if (StrUtil.isNotBlank(loginDTO.getNickname()) && !loginDTO.getNickname().equals(user.getNickname())) {
                log.info("更新用户昵称: {} -> {}", user.getNickname(), loginDTO.getNickname());
                user.setNickname(loginDTO.getNickname());
                needUpdate = true;
            }
            
            if (StrUtil.isNotBlank(loginDTO.getAvatar()) && !loginDTO.getAvatar().equals(user.getAvatar())) {
                log.info("更新用户头像: {}", loginDTO.getAvatar());
                user.setAvatar(loginDTO.getAvatar());
                needUpdate = true;
            }
            
            if (loginDTO.getGender() != null && !loginDTO.getGender().equals(user.getGender())) {
                log.info("更新用户性别: {} -> {}", user.getGender(), loginDTO.getGender());
                user.setGender(loginDTO.getGender());
                needUpdate = true;
            }
            
            if (needUpdate) {
                user.setUpdateTime(LocalDateTime.now());
                updateById(user);
                log.info("更新用户信息完成: {}", user.getNickname());
            }
        }
        
        // 生成token
        log.info("为用户生成token, ID: {}, 用户类型: 1", user.getId());
        String token = jwtUtil.generateToken(user.getId(), 1); // 1表示普通用户
        
        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", user);
        
        log.info("用户登录成功: {}, Token: {}", user.getNickname(), token);
        return result;
    }
    
    @Override
    public User getById(Long id) {
        return super.getById(id);
    }
    
    @Override
    public boolean updateById(User user) {
        user.setUpdateTime(LocalDateTime.now());
        return super.updateById(user);
    }
} 